package com.wy0924.listener;

import com.mysql.cj.xdevapi.Session;
import com.wy0924.bean.User;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.lang.reflect.Array;
import java.util.ArrayList;

@WebListener
public class SessionListener implements HttpSessionAttributeListener {
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        Object value = event.getValue();
        ServletContext servletContext = event.getSession().getServletContext();
        ArrayList<User> userList = (ArrayList<User>) servletContext.getAttribute("userList");
        if (userList == null) {
            userList = new ArrayList<>();
            servletContext.setAttribute("userList", userList);
        }
        userList.add((User) value);

    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        ServletContext servletContext = event.getSession().getServletContext();
        ArrayList<User> userList = (ArrayList<User>) servletContext.getAttribute("userList");
        userList.remove((User) (event.getValue()));
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        HttpSession session = event.getSession();
        User value = (User) event.getValue();
        User attribute = (User) session.getAttribute("user");
        ServletContext servletContext = session.getServletContext();
        ArrayList<User> userList = (ArrayList<User>) servletContext.getAttribute("userList");
        if (userList == null) {
            userList = new ArrayList<>();
            servletContext.setAttribute("userList", userList);
            userList.add(value);
        } else {
            userList.set(userList.indexOf(attribute), value);
        }
    }
}
